package cn.zhejianglao.oss.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.zhejianglao.oss.constants.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 没有 Token 输入 / 找不到用户数据的都会被拦截
 */
public class PostInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    // 在 WebMvcConfigurer 中进行注入
    public PostInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 Token
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            // 没有 Token 输入, 拦截
            throw new RuntimeException("没有 Token");
        }
        // 2. 基于 Token 获取用户数据
        String key = RedisConstants.USER_LOGIN_TOKEN_PREFIX + token;
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
//        // 3. 没有用户数据, 拦截
//        if (userMap.isEmpty()) {
//            throw new RuntimeException("登录已过期");
//        }
        if (stringRedisTemplate.opsForValue().get(key) == null) {
            throw new RuntimeException("登录已过期");
        }
        // 5. 放行
        return true;
    }
}
